package com.sugou.web.pages.directives;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.sugou.dao.support.bean.PagesSearchStatement;
import com.sugou.dao.support.bean.SearchStatement;
import com.sugou.services.support.Service;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component("hqlDirective")
public class HqlDirective implements TemplateDirectiveModel {

	private static final String STATEMENT="st";
	
	private static final String PARAMETER_VALUES="pv";
	
	private static final String LIMIT="limit";
	
	@Resource(name="baseService")
	private Service<Serializable> service;
	public void execute(Environment env, Map params, TemplateModel[] vars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Map<String, Object> prms=DirectiveUtils.unWrapperParams(params);
		String hql=prms.get(STATEMENT).toString();
		List<Serializable> pv=(List<Serializable>) prms.get(PARAMETER_VALUES);
		List<Number> limit=(List<Number>) prms.get(LIMIT);
		List<Serializable> res=null;
		CharSequence search=null;
		if(limit!=null&&limit.size()>0){
			search=new PagesSearchStatement(hql, pv, limit.get(0).intValue(), limit.size()>1?limit.get(1).intValue():20,null);
		}else{
			search=new SearchStatement(hql, pv);
		}
		res=this.service.search(search);
		env.setLocalVariable("_resList", ObjectWrapper.BEANS_WRAPPER.wrap(res));
		body.render(env.getOut());
	}
	public Service<Serializable> getService() {
		return service;
	}
	public void setService(Service<Serializable> service) {
		this.service = service;
	}
}
